package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.FeedbackMapper;
import com.itheima.dao.UserMapper;
import com.itheima.pojo.Feedback;
import com.itheima.pojo.User;
import com.itheima.service.FeedbackService;
import com.itheima.utils.IdWorker;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class FeedbackServiceImpl implements FeedbackService {

    @Resource
    private FeedbackMapper feedbackMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private IdWorker idWorker;

    /**
     * 删除反馈
     *
     * @Param Feedback
     */
    @Override
    public Integer delete(Feedback feedback) {
        return feedbackMapper.deleteByPrimaryKey(feedback);
    }

    /**
     * 编辑反馈
     *
     * @Param Feedback
     */
    @Override
    public Integer edit(Feedback feedback) {
        feedback.setUpdateTime(new Date());
        return feedbackMapper.updateByPrimaryKeySelective(feedback);
    }

    /**
     * 获取反馈列表
     *
     * @Param Feedback
     */
    @Override
    public Page<Feedback> getList(Feedback feedback) {
        Example example = new Example(Feedback.class);
        Example.Criteria criteria = example.createCriteria();
        if (feedback.getFeedbackStatus() != null) {
            criteria.andEqualTo("feedbackStatus",feedback.getFeedbackStatus());
        }

        if (feedback.getTitle() != null && !feedback.getTitle().equals("")) {
            criteria.andLike("title", "%"+feedback.getTitle()+"%");
        }

        PageHelper.startPage(feedback.getCurrentPage(), feedback.getPageSize());
        List<Feedback> feedbackList = feedbackMapper.selectByExample(example);
        if (feedbackList.size() > 0) {
            for (Feedback feedback1 : feedbackList) {
                User user = userMapper.selectByPrimaryKey(feedback1.getUserUid());
                feedback1.setUser(user);
            }
        }
        return (Page<Feedback>) feedbackList;
    }

    /**
     * 提交反馈
     *
     * @Param feedback
     */
    @Override
    public Integer addFeedback(Feedback feedback) {
        feedback.setUid(String.valueOf(idWorker.nextId()));
        feedback.setCreateTime(new Date());
        feedback.setUpdateTime(new Date());
        return feedbackMapper.insertSelective(feedback);
    }

    /**
     * 获取用户反馈
     */
    @Override
    public List<Feedback> getFeedbackList(String username) {
        User user = new User();
        user.setUserName(username);
        User user1 = userMapper.selectOne(user);
        Example example = new Example(Feedback.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userUid", user1.getUid());
        return feedbackMapper.selectByExample(example);
    }
}
